import Axios from 'axios';
import type {
    AxiosInstance,
    AxiosRequestConfig,
    CustomParamsSerializer
  } from "axios";

import { stringify } from "qs";

// 相关配置请参考：www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig: AxiosRequestConfig = {
    // 请求超时时间
    timeout: 10000,
    headers: {
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest"
    },
    // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
    paramsSerializer: {
      serialize: stringify as unknown as CustomParamsSerializer
    }
};

class Http{
    /** 保存当前Axios实例对象 */
  private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);

  /** 单独抽离的post工具函数 */
  public async post<T>(
    url: string,
    data?: object,
  ): Promise<T> {
    try {
        const response = await Axios.post(url, data, defaultConfig);
        return response.data;
      } catch (error) {
        console.error('Post Error:', error);
        throw error;
      }
  }

  /** 单独抽离的get工具函数 */
  public async get<T>(
    url: string,
    data?: object,
  ): Promise<T> {
    try {
        const response = await Axios.get(url, defaultConfig);
        return response.data;
      } catch (error) {
        console.error('Get Error:', error);
        throw error;
      }
  }
}

export const http = new Http();